import json
from django.http import JsonResponse, HttpResponse, Http404
from django.views import View
from rest_framework import status
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from .models import BookInfo
from .serializers import BookInfoSerializer

# Create your views here.
class BookListView(mixins.ListModelMixin, mixins.CreateModelMixin,GenericAPIView):

    serializer_class = BookInfoSerializer
    queryset = BookInfo.objects.all()

    def get(self, request):
        '''
        获取所有图书数据
        1,查询数据库获取所有图书数据
        2.将所有图书数据获取所有通过json进行返回
        '''

        # 查询数据库获取所有图书数据
        # books = BookInfo.objects.all()

        # 将所有图书数据通过json进行返回
        # books_li = []

        # for book in books:
        #     book_dict = {
        #         'id': book.id,
        #         'btitle': book.btitle,
        #         'bpub_date': book.bpub_date,
        #         'bread': book.bread,
        #         'bcomment': book.bcomment
        #     }
        #     books_li.append(book_dict)
        #
        #
        # return JsonResponse(books_li, safe=False)
        # serializer =BookInfoSerializer(books, many=True)
        # queryset = self.get_queryset()
        #
        # serializer = self.get_serializer(queryset, many = True)
        #
        # # return JsonResponse(serializer.data, safe=False)
        # return Response(serializer.data)

        return self.list(request)


    def post(self, request):
        '''
        新增一本图书数据
        1. 获取参数并进行校验
        2. 创建图书数据并保存到数据库
        3. 将新增图书数据通过json进行返回
        '''


        #1. 获取参数并进行校验
        # req_dict = json.loads(request.body.decode())

        # btitle = req_dict.get('btitle')
        # bpub_date = req_dict.get('bpub_date')
        #
        # book = BookInfo.objects.create(
        #     btitle=btitle,
        #     bpub_date=bpub_date
        # )
        #
        # # 将新增图书数据通过json进行返回
        # book_dict = {
        #     'id':book.id,
        #     'bittle':book.btitle,
        #     'bpub_data':book.bpub_date,
        #     'bread':book.bread,
        #     'bcomment':book.bcomment
        # }
        #
        # return JsonResponse(book_dict, status=201)
        # serializer = BookInfoSerializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # 创建图书对象并保存到数库
        # 反序列化－数据保存
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        #
        # serializer.save()
        #
        # # return JsonResponse(serializer.data, status=201)
        # return Response(serializer.data, status=status.HTTP_201_CREATED)
        return self.create(request)

class BookDetailView(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     GenericAPIView):

    serializer_class = BookInfoSerializer
    queryset = BookInfo.objects.all()

    def get(self, request, pk):
        '''
        获取指定图书数据(根据pk)
        1.查询数据库获取指定的图书数据
        2.将指定图书数据通过json进行返回
        '''

        # # 1.查询数据库获取指定的图书数据
        # try:
        #     book = BookInfo.objects.get(pk=pk)
        # except BookInfo.DoseNotExist:
        #     # 图书不存在
        #     # return JsonResponse({
        #     #     'detail':'not found'
        #     # }, status=404)
        #     raise Http404

        # 将指定图书数据通过json进行返回
        # book_dict = {
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date,
        #     'bread': book.bread,
        #     'bcomment': book.bcomment
        # }
        # return JsonResponse(book_dict)
        # serializer = BookInfoSerializer(book)
        # # return JsonResponse(serializer.data)
        # return Response(serializer.data)
        # instance = self.get_object()
        #
        # serializer = BookInfoSerializer(instance)
        #
        # return Response(serializer.data)
        return self.retrieve(request, pk)


    def put(self, request, pk):
        '''
        修改指定图书数据(根据pk)
        1.查询数据库获取指定的图书数据
        2.获取参数并进行校验
        3.修改图书数据并保存到数据库
        3.将修改图书数据通过json进行返回
        '''
        # 1.查询数据库获取指定的图书数据
        # try:
        #     book = BookInfo.objects.get(pk=pk)
        # except BookInfo.DoseNotExist:
        #     # 图书不存在
        #     return JsonResponse({
        #         'detail':'not found'
        #     }, status=404)
        # 获取参数并进行校验
        # req_dict = json.loads(request.body.decode())

        # btitle = req_dict.get('btitle')
        # bpub_date = req_dict.get('bpub_date')
        #
        # # ③ 修改图书数据并保存到数据库
        # book.btitle = btitle
        # book.bpub_date = bpub_date
        # book.save()
        #
        # # 将修改图书数据通过json进行返回
        # book_dict = {
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date,
        #     'bread': book.bread,
        #     'bcomment': book.bcomment
        # }
        # return JsonResponse(book_dict)
        # instance = self.get_object()
        # serializer = BookInfoSerializer(instance, data=request.data)
        # serializer.is_valid(raise_exception=True)
        #
        # serializer.save()
        #
        # # return JsonResponse(serializer.data)
        # return Response(serializer.data)
        return self.update(request, pk)

    def delete(self, request, pk):
        '''
        删除指定图书数据(根据pk)
        :1.查询数据库获取指定的图书数据
        2.删除指定图书数据
        3.返回响应
        '''
        # try:
        #     book = BookInfo.objects.get(pk=pk)
        # except BookInfo.DoseNotExist:
        #     # 图书不存在
        #     # return JsonResponse({
        #     #     'detail':'not found'
        #     # }, status=404)
        #     return Http404

        # 删除指定图书数据
        # book.delete()
        # return JsonResponse(status=204)
        # instance = self.get_object()
        # instance.delete()
        #
        # return Response(status=status.HTTP_204_NO_CONTENT)
        return self.destroy(request, pk)

class GoodsView(APIView):
    def get(self, request):
        '''
        抛出异常：测试自动处理异常功能时打开如下注释即可
        raise Http404
        raise serialzers.ValidationEffor('校验失败')
        '''

        return Response({'msg': 'hello'})